package com.xiaolei.library.Net.RetrofitExt.factorys;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.xiaolei.library.Utils.Log;

import java.io.IOException;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T>
{
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private Map<Class<?>, GsonConverterFactory.DataTypeListener<?>> typeListenerMap;

    public GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter, Map<Class<?>, GsonConverterFactory.DataTypeListener<?>> typeListenerMap)
    {
        this.gson = gson;
        this.adapter = adapter;
        this.typeListenerMap = typeListenerMap;
    }

    @Override
    public T convert(ResponseBody value) throws IOException
    {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try
        {
            T result = adapter.read(jsonReader);
            Class resultClass = result.getClass();
            GsonConverterFactory.DataTypeListener listener = typeListenerMap.get(resultClass);
            if (listener != null)
            {
                listener.onResponse(result);
            }
            if (jsonReader.peek() != JsonToken.END_DOCUMENT)
            {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        } finally
        {
            value.close();
        }
    }
}